# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

myStartsWith <- function(str, prefix){
    substring(str, 1, nchar(prefix)) == prefix
}

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

library(gplots)
library(Hmisc)
library(optparse)
library(dplyr)
library(ropls)
library(magrittr)
library(tibble)
library(stringr)

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

data <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
    select(- c("HMDB", "KEGG")) %>%
    filter(! startsWith(Name, "Unknown")) %>%
    select(c(- "Class")) %>%
    column_to_rownames("Metabolite") %>%
    as.data.frame()

head(data)
data <- t(data)

methods <- c("pearson", "spearman")
for (method in methods) {
    parent <- "Heatmap"
    createWhenNoExist(parent)
    fileName <- paste0(parent, "/Clustering_", method, "_all.pdf")
    pdf(fileName, width = 8, height = 8)
    corData <- rcorr(as.matrix(data), type = method)
    corData <- corData$r
    corData <- as.data.frame(corData)
    write.csv(corData, paste0(parent, "/", method, "_rvalues_all.csv"), col.names = NA, quote = FALSE)

    #取消x轴y轴label
    labCol = rep(NA, nrow(corData))
    labRow = rep(NA, nrow(corData))

    lmat <- NULL
    lwid <- NULL
    lhei <- NULL

    #color
    colors <- rev(colorRampPalette(RColorBrewer::brewer.pal(10, "RdBu"))(256))

    gene_dist = dist(as.matrix(1 - (corData)), method = "euclidean")
    hc_genes = hclust(gene_dist, method = "complete")
    rowv <- as.dendrogram(hc_genes)

    sample_dist <- dist(t((corData)))
    hc_samples <- hclust(sample_dist, method = "complete")
    colv = as.dendrogram(hc_samples)

    title <- paste0(method, " correlations")
    heatmap.2(as.matrix(corData), trace = "none", density.info = "none", Colv = colv, Rowv = rowv, labRow = labRow,
    labCol = labCol, lmat = lmat, lwid = lwid, lhei = lhei, col = colors, main = title)
    dev.off()
}

